//
//  LoginViewController.m
//  Romens.XSBalance
//
//  Created by 李美东 on 16/3/14.
//  Copyright © 2016年 孙博. All rights reserved.
//

#import "LoginViewController.h"
#import "WebRequest.h"
#import "WebRequestData.h"
#import "ToolHelper.h"
#import "SynUserandDepartment.h"
#import "RuntimeStatus.h"
#import "LoginSettingConfig.h"
#import "EMAlertView.h"
#import "DeviceSearchController.h"
@interface LoginViewController ()<UITextFieldDelegate, UINavigationControllerDelegate>
{
    NSString*Orgguid;
    BOOL IsSendSms;
}
@property  (strong, nonatomic) IBOutlet UITextField *usernameTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UIButton *registerButton;
@property (strong, nonatomic) IBOutlet UIButton *loginButton;

- (IBAction)doRegister:(id)sender;
- (IBAction)doLogin:(id)sender;



@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.IsShowUserInfo=NO;
    IsSendSms=YES;
    _usernameTextField=[[UITextField alloc]init];
    _passwordTextField=[[UITextField alloc]init];
    _registerButton=[UIButton buttonWithType:UIButtonTypeCustom];
    _loginButton=[UIButton buttonWithType:UIButtonTypeCustom];
    LoginSettingConfig *setting=[[LoginSettingConfig alloc]init];
    
    
    [setting SetUI:_usernameTextField pwd:_passwordTextField btnlogin:_loginButton btnregister:_registerButton viewController:self];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *phonenumber=[userDefaults objectForKey:@"phonenumber"];
    if (phonenumber==nil || [phonenumber isEqualToString:@""]) {
        [_usernameTextField becomeFirstResponder];
    }
    else
    {
        _usernameTextField.text=phonenumber;
        _passwordTextField.text=[userDefaults objectForKey:@"userpwd"];
    }
    [_registerButton addTarget:self action:@selector(doRegister:) forControlEvents:UIControlEventTouchUpInside];
    [_loginButton addTarget:self action:@selector(doLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    [self setTitleForButton];
    [self setupForDismissKeyboard];
    _usernameTextField.delegate = self;
    Orgguid=SystemOrgGuid;
    self.title =  @"登陆";
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    // app build版本
    NSString *app_build =[@"当前版本" stringByAppendingString:[infoDictionary objectForKey:@"CFBundleVersion"]];
    
    UILabel*Version=[UILabel new];
    Version.textAlignment=NSTextAlignmentCenter;
    Version.frame=CGRectMake(0,FULL_HEIGHT-100,FULL_WIDTH, 40);
    Version.text=app_build;
    [self.view addSubview:Version];
    self.navigationController.delegate = self;
}

- (void)dismiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)setTitleForButton{
    [self.registerButton setTitle:@"获取密码" forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//获取密码；
- (IBAction)doRegister:(id)sender {
    if(IsSendSms)
    {
        IsSendSms=NO;
        NSString *username = _usernameTextField.text;
        if(username.length==0)
        {
            [EMAlertView showAlertWithTitle:@"系统提示"
                                    message:@"手机号不能为空"
                            completionBlock:nil
                          cancelButtonTitle:@"确定"
                          otherButtonTitles:nil];
            IsSendSms=YES;
            return;
        }
        [self showHint:@"正在检测用户" yOffset:-(FULL_HEIGHT-110)];
        NSMutableDictionary*dic=[NSMutableDictionary new];
        [dic setValue:Orgguid forKey:@"ORGGUID"];
        [dic setValue:username forKey:@"PHONENUMBER"];
        
        NSString * json=[ToolHelper dictionaryToJson:dic];
        NSString *data=[@"QueryType=CheckPhoneNumber&UserGuid=&Params=" stringByAppendingString:json];
        [WebRequest jsonFormPOSTRequest:[SystemUrl stringByAppendingString:@"UnHandle"]  param:data success:^(id result) {
            
            [self hideHud];
            WebRequestData*data=(WebRequestData*)result;
            NSDictionary*resultdic= (NSDictionary*)[ToolHelper JsonToDictionary:data.RequestData];
            NSString*ISVALIDITY=[resultdic objectForKey:@"ISVALIDITY"];
            NSString*UserName=[resultdic objectForKey:@"NAME"];
            
            
            [self showHint:@"正在发送短信" yOffset:-(FULL_HEIGHT-110)];
            
            __block int timeout=60; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        IsSendSms=YES;
                        //设置界面的按钮显示 根据自己需求设置
                        [self setTitleForButton];
                    });
                }else{
                    NSString *strTime = [NSString stringWithFormat:@"发送密码(%d)", timeout];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        [self.registerButton setTitle:strTime forState:UIControlStateNormal];
                    });
                    timeout--;
                    
                }
            });
            dispatch_resume(_timer);
            
            
            int Flag=[ISVALIDITY intValue]-1;
            [dic setValue:[NSString stringWithFormat:@"%d",Flag] forKey:@"FLAG"];
            [dic setValue:UserName forKey:@"USERNAME"];
            NSString * json=[ToolHelper dictionaryToJson:dic];
            NSString *datastring=[@"QueryType=sendsms&UserGuid=&Params=" stringByAppendingString:json];
            [WebRequest jsonFormPOSTRequest:[SystemUrl stringByAppendingString:@"UnHandle"]  param:datastring success:^(id result) {
                WebRequestData*BackResult=(WebRequestData*)result;
                [self hideHud];
                if(BackResult.Error.length>0)
                {
                    [self showHint:BackResult.Error yOffset:-(FULL_HEIGHT-110)];
                }
                else
                {
                    NSDictionary*resultdic= (NSDictionary*)[ToolHelper JsonToDictionary:BackResult.RequestData];
                    NSString*result= [resultdic objectForKey:@"SMSRESULT"];
                    if([result isEqualToString:@"1"])
                    {
                        [self showHint:@"短信发送成功请注意查收" yOffset:-(FULL_HEIGHT-110)];
                        
                    }
                    else
                    {
                        
                        [self showHint:[NSString stringWithFormat:@"短信发送失败:错误编码%@",result] yOffset:-(FULL_HEIGHT-110)];
                        
                    }
                }
            }];
        }];
    }
}

//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    NSMutableDictionary*dic=[NSMutableDictionary new];
    [dic setValue:username forKey:@"PHONENUMBER"];
    [dic setValue:Orgguid forKey:@"ORGGUID"];
    
    NSString * json=[ToolHelper dictionaryToJson:dic];
    NSString *data=[@"QueryType=CheckPhoneNumber&UserGuid=&Params=" stringByAppendingString:json];
    [self showHudInView:self.view hint:@"正在检测手机号..."];
    [WebRequest jsonFormPOSTRequest:[SystemUrl stringByAppendingString:@"UnHandle"]  param:data success:^(id result) {
        [self hideHud];
        WebRequestData*data=(WebRequestData*)result;
        if(data.Error.length>0)
        {
            [EMAlertView showAlertWithTitle:NSLocalizedString(@"prompt", @"Prompt")
                                    message:data.Error
                            completionBlock:nil
                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                          otherButtonTitles:nil];
            return ;
        }
        
        NSDictionary*dic= (NSDictionary*)[ToolHelper JsonToDictionary:data.RequestData];
        NSString*ISVALIDITY= [dic objectForKey:@"ISVALIDITY"];
        NSString*UserName=[dic objectForKey:@"NAME"];
        NSString*OpreationName=[dic objectForKey:@"USERNAME"];
        
        NSString* userGuid=[ToolHelper GetUserGUid:Orgguid name:UserName pwd:password];
        if([ISVALIDITY isEqualToString:@"0"])
        {
            [EMAlertView showAlertWithTitle:NSLocalizedString(@"prompt", @"Prompt")
                                    message:@"当前用户不存在"
                            completionBlock:nil
                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                          otherButtonTitles:nil];
            return;
        }
        if([ISVALIDITY isEqualToString:@"1"])
        {
            [EMAlertView showAlertWithTitle:NSLocalizedString(@"prompt", @"Prompt")
                                    message:@"当前用户尚未激活，请点击获取密码，使用短信密码登录"
                            completionBlock:nil
                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                          otherButtonTitles:nil];
            return;
            
        }
        //ISVALIDITY
        
        NSString* Loginpassword=  [ToolHelper md5forX:[[ToolHelper md5forX:password] stringByAppendingString:@"0"]];
        //异步登陆账号
        NSString* IMKey= [dic objectForKey:@"NAME"];
        [self showHudInView:self.view hint:@"正在登录..."];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        //存储时，除NSNumber类型使用对应的类型意外，其他的都是使用setObject:forKey:
        [userDefaults setObject:IMKey forKey:@"LOGINNAME"];
        [userDefaults setObject:userGuid forKey:@"userguid"];
           //     [userDefaults setObject:OpreationName forKey:@"username"];
   //     [userDefaults setObject:@"888888" forKey:@"huanxinid"];
        if([ISVALIDITY isEqualToString:@"2"])
        {
            NSMutableDictionary * loginDic = [NSMutableDictionary new];
            [loginDic setObject:Orgguid forKey:@"ORGGUID"];
            [loginDic setObject:Loginpassword forKey:@"PWD"];
            [loginDic setObject:UserName forKey:@"USERNAME"];
            
            [self Request:[SystemUrl stringByAppendingString:@"/UnHandle"] queryType:@"UserLoginHealth" postData:loginDic success:^(id data){
                
                WebRequestData *data1=(WebRequestData*)data;
                if(!isEmptyString(data1.Error))
                {
                    [self SHowMessage:data1.Error type:showError];
                    return ;
                }
                if (![data1.RequestData isEqualToString:@"\"\""]) {
                    NSDictionary * errorDic=(NSDictionary*)[ToolHelper JsonToDictionary:data1.RequestData];
                    [EMAlertView showAlertWithTitle:@"系统提示"
                                            message:[errorDic objectForKey:@"ERROR"]
                                    completionBlock:nil
                                  cancelButtonTitle:@"确定"
                                  otherButtonTitles:nil];
                    return ;
                    
                }
                [userDefaults removeObjectForKey:@"phonenumber"];
                [userDefaults removeObjectForKey:@"userpwd"];
                
                [userDefaults setObject:_usernameTextField.text  forKey:@"phonenumber"];
                [userDefaults setObject:Loginpassword forKey:@"userpwd"];

                if(self._LoginResaultBlock)
                {
                    self._LoginResaultBlock();
                }


            }];
        }
        
        [self hideHud];
        
        return;
        
    }];
}

     

//登陆
- (IBAction)doLogin:(id)sender {
    if (![self isEmpty]) {
        [self.view endEditing:YES];
        //支持是否为中文
        if ([self.usernameTextField.text isChinese]) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:NSLocalizedString(@"login.nameNotSupportZh", @"Name does not support Chinese")
                                  message:nil
                                  delegate:nil
                                  cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                  otherButtonTitles:nil];
            
            [alert show];
            
            return;
        }
        
        [self loginWithUsername:_usernameTextField.text password:_passwordTextField.text];
    }
}
//判断账号和密码是否为空
- (BOOL)isEmpty{
    BOOL ret = NO;
    NSString *username = _usernameTextField.text;
    NSString *password = _passwordTextField.text;
    
    
    if (username.length == 0 || password.length == 0) {
        ret = YES;
        [EMAlertView showAlertWithTitle:NSLocalizedString(@"prompt", @"Prompt")
                                message:NSLocalizedString(@"login.inputNameAndPswd", @"Please enter username and password")
                        completionBlock:nil
                      cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                      otherButtonTitles:nil];
    }
    
    return ret;
}


#pragma  mark - TextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField == _usernameTextField) {
        _passwordTextField.text = @"";
    }
    
    return YES;
}

//-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
//{
//    [viewController viewWillAppear:animated];
//}

@end
